package com.lh.pospi.x_store.ui.inventory;

import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.InputType;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.Spinner;
import android.widget.Switch;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.lh.pospi.x_store.Interface.StatusListener;
import com.lh.pospi.x_store.R;
import com.lh.pospi.x_store.adapter.PurchaseAdapter;
import com.lh.pospi.x_store.app.MyApp;
import com.lh.pospi.x_store.base.BaseActivity;
import com.lh.pospi.x_store.greendao.GoodsBeanDao;
import com.lh.pospi.x_store.modle.BillBean;
import com.lh.pospi.x_store.modle.GoodsBean;
import com.lh.pospi.x_store.modle.MarktBean;
import com.lh.pospi.x_store.modle.SupBean;
import com.lh.pospi.x_store.ui.GoodsSearchActivity;
import com.lh.pospi.x_store.utils.BillUtil;
import com.lh.pospi.x_store.utils.Constant;
import com.lh.pospi.x_store.utils.LoadingUtil;
import com.lh.pospi.x_store.view.DialogGoods;
import com.qmuiteam.qmui.widget.roundwidget.QMUIRoundButton;
import com.vondear.rxtool.RxDataTool;
import com.vondear.rxtool.RxKeyboardTool;
import com.vondear.rxtool.RxLogTool;
import com.vondear.rxtool.RxTimeTool;
import com.vondear.rxtool.view.RxToast;
import com.vondear.rxui.view.dialog.RxDialogEditSureCancel;
import com.vondear.rxui.view.dialog.RxDialogSureCancel;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

public class InventoryDetailActivity extends BaseActivity {
    @BindView(R.id.rv_goods)
    RecyclerView recyclerView;
    @BindView(R.id.spinner)
    Spinner spinner;
    @BindView(R.id.spinner_sup)
    Spinner spinner_sup;
    @BindView(R.id.tv_amount)
    TextView tv_amount;
    @BindView(R.id.tv_num)
    TextView tv_num;
    @BindView(R.id.tv_date)
    TextView tv_date;
    @BindView(R.id.et_code)
    EditText et_code;
    @BindView(R.id.et_memo)
    EditText et_memo;
    @BindView(R.id.fab_button)
    FloatingActionButton fab_button;
    @BindView(R.id.btn_save)
    QMUIRoundButton btn_save;
    @BindView(R.id.btn_new)
    QMUIRoundButton btn_new;
    @BindView(R.id.ll_sup)
    LinearLayout ll_sup;
    @BindView(R.id.tv_inmark)
    TextView tv_inmark;
    @BindView(R.id.tv_sup)
    TextView tv_sup;
    @BindView(R.id.scan_auto)
    Switch scan_auto;
    @BindView(R.id.de_num)
    TextView de_num;
    @BindView(R.id.rl_tab1)
    RelativeLayout rl_tab1;
    @BindView(R.id.ll_tab2)
    LinearLayout ll_tab2;
    private boolean isAuto;
    private List<GoodsBean> goodsBeans;
    private PurchaseAdapter adapter;
    private String markId;
    private String supId;
    private String memo;
    private String marketname;
    private String supname;
    private List<MarktBean> marktBeans;
    private List<MarktBean> supBeans;
    private ArrayAdapter<MarktBean> marktBeanArrayAdapter;
    private ArrayAdapter<MarktBean> outArrayAdapter;
    private BillBean billBean;
    private String billType = Constant.TYPE_BH;
    private boolean isup = false;

    @Override
    protected int getContentView() {
        return R.layout.activity_purchase_detail;
    }

    @Override
    protected void init(Bundle savedInstanceState) {
        billType = getIntent().getStringExtra(Constant.INVENTORY);
        if (billType.equals(Constant.TYPE_BH)||billType.equals(Constant.TYPE_PD)) {
            ll_sup.setVisibility(View.GONE);
        } else {
            tv_inmark.setText("调入门店:");
            tv_sup.setText("调出门店:");
        }

        goodsBeans = new ArrayList<>();
        tv_date.setText(RxTimeTool.getCurrentDateTime("yyyy-MM-dd"));//**MMddhhmmss
        getTopBar().setTitle("详情");

        scan_auto.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
                isAuto = b;
            }
        });

        initTitle();
        setRight();
        initView();
        initSpinner();
        initData();
    }
    private void initTitle() {
        switch (billType) {
            case Constant.TYPE_BH:
                getTopBar().setTitle("补货单");
                break;
            case Constant.TYPE_DB:
                getTopBar().setTitle("调拨单");
                break;
            case Constant.TYPE_PD:
                getTopBar().setTitle("盘点单");
                break;
        }
    }
    private void initData() {
        billBean = (BillBean) getIntent().getSerializableExtra("bill");
        if (billBean == null) {
            return;
        }
        if (billBean.getStatus().equals("1")) {
           setUpOver();
        }
        tv_date.setText(billBean.getBillrq());
        for (int i = 0; i < marktBeans.size(); i++) {
            if (marktBeans.get(i).getCode().equals(billBean.getMarket())) {
                Collections.swap(marktBeans, 0,i);
                break;
            }
        }
        for (int i = 0; i < supBeans.size(); i++) {
            if (supBeans.get(i).getCode().equals(billBean.getSup())) {
                Collections.swap(supBeans, 0,i);
                break;
            }
        }
        marktBeanArrayAdapter.notifyDataSetChanged();
        et_memo.setText(billBean.getMemo());
        goodsBeans.clear();
        List<GoodsBean> beans = new Gson().fromJson(billBean.getBilldetail(), new TypeToken<List<GoodsBean>>() {
        }.getType());
        RxLogTool.d("数量："+beans.size());
        goodsBeans.addAll(beans);
        update();
    }

    private void initView() {
        recyclerView.setLayoutManager(new LinearLayoutManager(mContext));
        adapter = new PurchaseAdapter(R.layout.item_goods, goodsBeans);
        recyclerView.setAdapter(adapter);
        adapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                showItemDialog(goodsBeans.get(position));
            }
        });
        adapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, final int position) {
                if (isup) {
                    return;
                }
                final RxDialogSureCancel rxDialogSureCancel = new RxDialogSureCancel(mContext);
                rxDialogSureCancel.setTitle("提示");
                rxDialogSureCancel.setContent("是否删除-" + goodsBeans.get(position).getName() + "?");
                rxDialogSureCancel.setSureListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        goodsBeans.remove(position);
                        update();
                        rxDialogSureCancel.dismiss();
                    }
                });
                rxDialogSureCancel.setCancelListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        rxDialogSureCancel.dismiss();
                    }
                });
                rxDialogSureCancel.show();

            }
        });
    }

    private void initSpinner() {
        marktBeans = MyApp.getInstance().getDaoSession().getMarktBeanDao().loadAll();
        supBeans = MyApp.getInstance().getDaoSession().getMarktBeanDao().loadAll();
        marktBeanArrayAdapter = new ArrayAdapter<MarktBean>(mContext, android.R.layout.simple_list_item_1, marktBeans);
        outArrayAdapter = new ArrayAdapter<MarktBean>(mContext, android.R.layout.simple_list_item_1, supBeans);
        spinner.setAdapter(marktBeanArrayAdapter);
        spinner_sup.setAdapter(outArrayAdapter);
        spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
                markId = marktBeans.get(i).getCode();
                marketname = marktBeans.get(i).getName();
            }

            @Override
            public void onNothingSelected(AdapterView<?> adapterView) {

            }
        });
        spinner_sup.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
                supId = supBeans.get(i).getCode();
                supname = supBeans.get(i).getName();
            }

            @Override
            public void onNothingSelected(AdapterView<?> adapterView) {

            }
        });

        et_memo.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View view, MotionEvent motionEvent) {
                et_memo.setFocusableInTouchMode(true);
                return false;
            }
        });
        et_code.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView textView, int i, KeyEvent keyEvent) {
                search();
                return false;
            }
        });
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        List<GoodsBean> beans = (List<GoodsBean>) intent.getSerializableExtra(GoodsSearchActivity.MARK);
        update(beans);
    }

    @OnClick({R.id.fab_button, R.id.tv_date, R.id.btn_save, R.id.tv_search,R.id.de_num,R.id.btn_new,R.id.et_delete})
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.et_delete:
                et_code.setText("");
                break;
            case R.id.btn_new:
                billBean = null;
                goodsBeans.clear();
                update();
                break;
            case R.id.fab_button:
                Intent intent = new Intent(this, GoodsSearchActivity.class);
                intent.putExtra(GoodsSearchActivity.MARK, GoodsSearchActivity.MARK_INVENTORY);
                startActivity(intent);
                break;
            case R.id.tv_date:
                showTimer(tv_date);
                break;
            case R.id.btn_save:
                save();

                break;
            case R.id.tv_search:
                search();
                break;
            case R.id.de_num:
                new DialogGoods(mContext).showDeNum(de_num.getText().toString(), new DialogGoods.Listener() {
                    @Override
                    public void getNum(int num) {
                        de_num.setText(String.valueOf(num));
                    }
                });
                break;
        }
    }

    private void save() {
        memo = et_memo.getText().toString().trim();
        if (goodsBeans.size() == 0) {
            RxToast.warning("请添加商品");
            return;
        }
        if (billBean == null) {
            BillUtil.savebill(mContext,
                    tv_date.getText().toString(),
                    markId,
                    supId,
                    memo,
                    goodsBeans,
                    billType,
                    marketname,
                    supname,
                    new StatusListener() {
                        @Override
                        public void upSuccess(String msg) {

                        }

                        @Override
                        public void upFailed(String msg) {
                            RxToast.normal(msg);
                        }

                        @Override
                        public void saveSuccess(BillBean bean) {
                            billBean = bean;
                            RxToast.normal("保存成功");
                        }
                    });
        } else {
            BillUtil.updatebill(mContext,
                    tv_date.getText().toString(),
                    markId,
                    supId,
                    memo,
                    marketname,
                    supname,
                    goodsBeans,
                    billBean, new StatusListener() {
                        @Override
                        public void upSuccess(String msg) {
                            RxToast.normal(msg);
                        }

                        @Override
                        public void upFailed(String msg) {
                            RxToast.normal(msg);
                        }

                        @Override
                        public void saveSuccess(BillBean bean) {

                        }
                    });
        }
    }

    private void search() {
        String code = et_code.getText().toString();
        if (code.isEmpty()) {
//            RxToast.warning("请输入条码");
            return;
        }
        MyApp.getInstance().getDaoSession().getGoodsBeanDao().detachAll();
        GoodsBean bean = MyApp.getInstance().getDaoSession().getGoodsBeanDao().queryBuilder()
                .where(GoodsBeanDao.Properties.Barcode.eq(code)).limit(1).unique();
        if (bean != null) {
            et_code.setText("");
            if (isAuto) {
                bean.setNum(Integer.parseInt(de_num.getText().toString()));
                update(bean);
            } else {
                showDialog(bean);
            }
        } else {
            RxToast.warning("条码有误");
        }
    }

    private void update(List<GoodsBean> beans) {
        if (beans != null) {
            goodsBeans.addAll(0,beans);

            update();
        }
    }
    private void update(GoodsBean bean) {
        boolean no = false;
        for (GoodsBean goodsBean : goodsBeans) {
            if (bean.getCode().equals(goodsBean.getCode())) {
                goodsBean.setNum(goodsBean.getNum() + bean.getNum());
                no = true;
                break;
            }
        }
        if (!no) {
            goodsBeans.add(0,bean);
        }
        update();
    }
    private void update() {

        int num = 0;
        double amount = 0;
        for (GoodsBean bean : goodsBeans) {
            num += bean.getNum();
            amount += bean.getNum() * Double.parseDouble(bean.getLsj());
        }
        tv_amount.setText("合计金额：" + amount);
        tv_num.setText("合计件数：" + num);

        adapter.notifyDataSetChanged();
        recyclerView.setFocusableInTouchMode(true);

    }

    private void showDialog(final GoodsBean bean) {
        new DialogGoods(mContext).show(bean, new DialogGoods.Listener() {
            @Override
            public void getNum(int num) {
                bean.setNum(num);
                goodsBeans.add(0,bean);
                update();
            }
        });
    }
    private void closeKey(EditText editText){
        RxKeyboardTool.hideSoftInput(mContext, editText);

    }
    private void showItemDialog(final GoodsBean bean) {
        if (isup) {
            return;
        }
        //提示弹窗
        final RxDialogEditSureCancel rxDialogEditSureCancel = new RxDialogEditSureCancel(this);
        rxDialogEditSureCancel.setTitle(bean.getName());
        rxDialogEditSureCancel.getEditText().setHint("请输入数量");
        rxDialogEditSureCancel.getEditText().setText(String.valueOf(bean.getNum()));
        rxDialogEditSureCancel.getEditText().setInputType(InputType.TYPE_CLASS_NUMBER);
        rxDialogEditSureCancel.getEditText().setSelectAllOnFocus(true);
        rxDialogEditSureCancel.setSure("取消");
        rxDialogEditSureCancel.setCancel("确定");
        rxDialogEditSureCancel.getCancelView().setTextColor(getResources().getColor(R.color.app_color_blue));
        rxDialogEditSureCancel.getSureView().setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                closeKey(rxDialogEditSureCancel.getEditText());


                rxDialogEditSureCancel.cancel();

            }
        });
        rxDialogEditSureCancel.getCancelView().setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String s = rxDialogEditSureCancel.getEditText().getText().toString().trim();
                if (RxDataTool.isInteger(s)) {
                    bean.setNum(Integer.parseInt(s));
                    update();
                } else {
                    RxToast.warning("请输入正确的数量");
                }

                closeKey(rxDialogEditSureCancel.getEditText());
                rxDialogEditSureCancel.cancel();


            }
        });
        rxDialogEditSureCancel.show();
        RxKeyboardTool.toggleSoftInput(mContext,rxDialogEditSureCancel.getEditText());
    }
    private void setUpOver() {
        isup = true;
        fab_button.hide();
        getTopBar().setSubTitle("已上传");
        getTopBar().removeAllRightViews();

        btn_save.setVisibility(View.GONE);
        rl_tab1.setVisibility(View.GONE);
        ll_tab2.setVisibility(View.GONE);
        btn_new.setVisibility(View.GONE);
    }
    private void setRight() {
        Button upButton = getTopBar().addRightTextButton("上传", R.mipmap.icon_up);
        upButton.setTextColor(getResources().getColor(R.color.white));
        upButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (billBean != null) {
                    final LoadingUtil util = new LoadingUtil(mContext);
                    util.show("上传中");
                    BillUtil.upbill(billBean, new StatusListener() {
                        @Override
                        public void upSuccess(String msg) {
                            util.close();
                            RxToast.normal("上传成功");
                            setUpOver();
                        }

                        @Override
                        public void upFailed(String msg) {

                        }

                        @Override
                        public void saveSuccess(BillBean bean) {

                        }
                    });
                } else {
                    RxToast.warning("请先保存单据");
                }

            }
        });
    }
}
